package com.gingko.duominuo.data.datastore

import androidx.datastore.core.DataStore
import androidx.datastore.createDataStore
import com.gingko.duominuo.proto.SettingPreferences
import com.gingko.duominuo.App
import com.gingko.duominuo.utils.loge
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import java.io.IOException


object DataStoreHelper {
    private val dataStore: DataStore<SettingPreferences> =
        App.instance.createDataStore("setting_prefs.pb", SettingsSerializer)

    private val settingPreferencesFlow: Flow<SettingPreferences> = dataStore.data
        .catch { exception ->
            if (exception is IOException) {
                exception.loge()
                emit(SettingPreferences.getDefaultInstance())
            } else {
                throw exception
            }
        }


    suspend fun getUserId(): String? {
        return settingPreferencesFlow.map { it.userId }.firstOrNull()
    }

    suspend fun saveUserId(userId: String) {
        dataStore.updateData { currentSettings ->
            currentSettings.toBuilder()
                .setUserId(userId)
                .build()
        }
    }

    suspend fun isLogin(): Boolean {
        return settingPreferencesFlow.map { it.isLogin }.firstOrNull() ?: false
    }

    suspend fun saveIsUseX5Kernel(isUseX5Kernel: Boolean) {
        dataStore.updateData { currentSettings ->
            currentSettings.toBuilder()
                .setIsUseX5Kernel(isUseX5Kernel)
                .build()
        }
    }

    suspend fun isUseX5Kernel(): Boolean {
        return settingPreferencesFlow.map { it.isUseX5Kernel }.firstOrNull() ?: true
    }

    suspend fun saveIsLogin(isLogin: Boolean) {
        if (isLogin) {
            saveIsUseX5Kernel(true)
        }
        dataStore.updateData { currentSettings ->
            currentSettings.toBuilder()
                .setIsLogin(isLogin)
                .build()
        }
    }


}



